<?php
header('Content-Type: application/json');
require_once 'config.php';

$response = ['code' => 200];

// 验证登录状态
session_start();
if (!isset($_SESSION['username']) || $_SESSION['username'] == "" ) {
    http_response_code(401);
    die(json_encode(['code' => 401, 'message' => '请先登录']));
}

// 获取并验证参数
$monthly = isset($_POST['monthly']) ? floatval($_POST['monthly']) : 0;
$yearly = isset($_POST['yearly']) ? floatval($_POST['yearly']) : 0;
$lifetime = isset($_POST['lifetime']) ? floatval($_POST['lifetime']) : 0;

try {
    // 检查是否存在记录
    $check = $conn->query("SELECT COUNT(*) AS count FROM price_settings");
    $row = $check->fetch_assoc();
    
    if ($row['count'] > 0) {
        $stmt = $conn->prepare("UPDATE price_settings SET 
            monthly_price = ?, 
            yearly_price = ?, 
            lifetime_price = ?");
    } else {
        $stmt = $conn->prepare("INSERT INTO price_settings 
            (monthly_price, yearly_price, lifetime_price) 
            VALUES (?, ?, ?)");
    }
    
    $stmt->bind_param("ddd", $monthly, $yearly, $lifetime);
    $stmt->execute();
    
    if ($stmt->affected_rows === -1) {
        throw new Exception("保存失败");
    }
    
    $response['message'] = '价格设置保存成功';
} catch (Exception $e) {
    $response['code'] = 500;
    $response['message'] = '数据库错误: ' . $e->getMessage();
} finally {
    $conn->close();
}

echo json_encode($response);
?>